require "acts_as_dynamic_method/version"

module ActsAsDynamicMethod

  module ClassMethods
    
    attr_accessor :json_field

    def acts_as_dynamic_method(options = {})
      self.json_field = (options[:json_field] || :params).to_s
      include ActsAsDynamicMethod::InstanceMethods
    end
  end
  
  module InstanceMethods
   def fields
      field_name = self.class.json_field 
      field = self.method(field_name)
      @fields ||= ((field.call.is_a?(String) ? JSON.parse(field.call) : field.call) || {})
    end

    def use(field)
      fields[field]
    end

    def set(field, value)
      fields unless @fields
      @fields[field] = value
    end  

    def json_keys
      fields.keys
    end

    def to_json
      fields.to_json
    end

    def method_missing(meth, *args, &block)
      method_name = meth.to_s
      if json_keys.include?(method_name)
        self.use(method_name)
      elsif json_keys.include?(method_name.gsub!('=', ''))
        self.set(method_name, args.first)
      elsif method_name.match(/\?$/)
        self.json_keys.include?(method_name.gsub('?', ''))
      else
        super
      end
    end

  end
  
  if defined?(ActiveRecord::Base)
    ActiveRecord::Base.send :extend, ActsAsDynamicMethod::ClassMethods 
  else 
    Object.send :include, ActsAsDynamicMethod::ClassMethods
  end

  # def self.included(receiver)
  #   receiver.extend  ClassMethods
  #   receiver.send :include, InstanceMethods
  # end


end